<?php
declare (strict_types = 1);

namespace app\common\listener;

use think\facade\Db;
use think\facade\Request;

class WsTest
{

    public function check_str($str, $substr)
    {
        $nums = substr_count($str, $substr);
        if ($nums >= 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event, \think\swoole\Websocket $ws)
    {
        $this->chat_message =   app('app\common\model\chat\ChatMessage');
        $this->system_admin =  app('app\common\model\system\SystemAdmin');
        //echo 'test';
        //var_dump($event);
        //也可以 $ws = app('think\swoole\Websocket');
        // $ws = Container对象->make('think\swoole\Websocket');
        // $event ：接收到的数据


        //获取发送者的客户端id
        $from_fd = Db::name('chat')->where('user_id', $event['from'])->value('fd');
        //获取接收者的客户端id
        $to_fd = Db::name('chat')->where('user_id', $event['to'])->value('fd');

        //获取当前接待人数

         if($event['type'] == 1){//用户对商家
             $count = $this->chat_message->where(['to_id'=>$event['to'],'type'=>1])->group('from_id')->count();
             $this->system_admin->where('id',$event['to'])->save(['reception_number'=>$count]);

         }elseif($event['type'] == 2){//用户对平台
             $count = $this->chat_message->where(['to_id'=>$event['to'],'type'=>2])->group('from_id')->count();
             $this->system_admin->where('id',$event['to'])->save(['reception_number'=>$count]);
          }



        if(@$event['first'] !=1 && $event['message'] !='' && $event['to'] >0){ //除了首次进来问候语

            //检索关键词有敏感词不给予发布
            $content = $event['message'];

            $word = app('app\common\model\system\Word');
            $list = $word->where('status',1)->column('id','content');
            $keys = array_keys($list);
            //var_dump($keys);
            if($event['msgtype'] == !3){
                foreach($keys as $k=>$v){

                    if(substr_count(base64_decode($content),$v) > 0){

                        $word->where('id',$list[$v])->inc('number')->update();
                        $ws->to(intval($to_fd))->emit('testcallback', [
                            'error' => [
                                'status' => '0',
                                'error' => '含有敏感词',

                            ]
                        ]);
                        return;
                    }
                }
            }


            //消息入库
            Db::name('chat_message')->insert([
                'from_id' => $event['from'],
                'to_id' => $event['to'],
                'type' => $event['type'],//1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户；
                'msgtype' => $event['msgtype'],
                'create_time' => time(),
                'content' => $event['message'],
                'real_content' => @$event['real_content']
            ]);
            // 发送给消息
            $ws->to(intval($to_fd))->emit('testcallback', [
                'from' => [
                    'id' => $event['from'],
                    'fd' => $from_fd,
                    'nickanme' => '发送者',
                    // ...
                ],
                'to' => [
                    'id' => $event['to'],
                    'fd' => intval($to_fd),
                    'nickname' => '接收者',
                    //...
                ],
                'message' => [
                    'id' => 888,
                    'create_time' => date('Y-m-d H:i:s'),
                    'content' => $event['message']
                ]
            ]);
        }


        //判断自动回复 $event['type'],//1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户；
        if (($event['type'] == 1 || $event['type'] ==2) && (isset($event['first']) && $event['first'] == 2) ) {
            //查询是否开启自动回复
            $info = Db::name('system_admin')->where('id', $event['to'])->field('id,message_state,message,message_time')->find();
            if($event['type'] ==2) $ty =4;
            if($event['type'] ==1) $ty =3;
           /* $message = Db::name('chat_message')
                ->whereTime('create_time','>',$info['message_time'])
                ->where(['from_id'=>$event['to'],'to_id'=>$event['from'],'type'=>$ty,'msgtype'=>1])
                ->find();*/
            //var_dump(!$message);
            //查询自动回复期间是否发送过
            if ($info['message_state'] == 1 /*&& !$message*/) {
                $ws->to(intval($to_fd))->emit('testcallback', [
                    'from' => [
                        'id' => $event['to'],
                        'fd' => intval($to_fd),
                        'nickanme' => '发送者',
                        // ...
                    ],
                    'to' => [
                        'id' => $event['from'],
                        'fd' => $from_fd,
                        'nickname' => '接收者',
                        //...
                    ],
                    'message' => [
                        'id' => 888,
                        'create_time' => date('Y-m-d H:i:s'),
                        'content' => base64_encode($info['message'])
                    ]
                ]);
                //消息入库
                Db::name('chat_message')->insert([
                    'from_id' => $event['to'],
                    'to_id' => $event['from'],
                    'type' => $ty,//1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户；
                    'msgtype' => 1, //自动回复
                    'create_time' => time(),
                    'real_content' => @$info['message'],
                    'content' => base64_encode($info['message'])
                ]);
            }
        }

        //判断欢迎语 $event['type'],//1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户；
        if (($event['type'] == 1 || $event['type'] ==2) && (isset($event['first']) && $event['first'] == 1)) {

            //查询是否开启自动回复
            $first_message_info = Db::name('system_admin')->where('id', $event['to'])->field('id,first_message_state,first_message,first_message_time')->find();
            if($event['type'] ==2) $ty =4;
            if($event['type'] ==1) $ty =3;

            //查询自动回复期间是否发送过
            if ($first_message_info['first_message_state'] == 1) {
                $ws->to(intval($to_fd))->emit('testcallback', [
                    'from' => [
                        'id' => $event['to'],
                        'fd' => intval($to_fd),
                        'nickanme' => '发送者',
                        // ...
                    ],
                    'to' => [
                        'id' => $event['from'],
                        'fd' => $from_fd,
                        'nickname' => '接收者',
                        //...
                    ],
                    'message' => [
                        'id' => 888,
                        'create_time' => date('Y-m-d H:i:s'),
                        'content' => base64_encode($first_message_info['first_message'])
                    ]
                ]);
                //消息入库
                Db::name('chat_message')->insert([
                    'from_id' => $event['to'],
                    'to_id' => $event['from'],
                    'type' => $ty,//1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户；
                    'msgtype' => 1, //自动回复
                    'create_time' => time(),
                    'real_content' => @$first_message_info['first_message'],
                    'content' => base64_encode($first_message_info['first_message'])
                ]);
            }
        }
    }



        // 获取当前发送客户端的fd.
        //var_dump($ws->getSender());

        // 发送给指定的fd的客户端 包括发送者


        //$ws->to(intval($event['to']))->emit('testcallback', $event['message']);
        //发送给指定的fd客户端，数组包含
        //$ws->to([1,2,3])->emit('testcallback', $event['message']);
        //发送给所有客户端 广播 除了发送者  参数：事件名  自定义的发送数据
        //$ws->broadcast()->emit('testcallback', $event['message']);

        // 模拟客户端给另外一个客户端发送数据
        //$ws->setSender(2)->to(3)->emit('testcallback', $event['message']);
        // 获取Swoole\WebSocket\Server
//
}